package com.shop.loan.oss;

import cn.ucloud.ufile.UfileClient;
import cn.ucloud.ufile.api.ApiError;
import cn.ucloud.ufile.api.object.ObjectConfig;
import cn.ucloud.ufile.auth.ObjectAuthorization;
import cn.ucloud.ufile.auth.UfileObjectLocalAuthorization;
import cn.ucloud.ufile.bean.PutObjectResultBean;
import cn.ucloud.ufile.bean.UfileErrorBean;
import cn.ucloud.ufile.exception.UfileClientException;
import cn.ucloud.ufile.exception.UfileServerException;
import cn.ucloud.ufile.http.UfileCallback;
import cn.ucloud.ufile.util.StorageType;
import okhttp3.Request;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class UCloudUtil {

    @Value("${api.ucloud.oss.publicKey}")
    private String publicKey;

    @Value("${api.ucloud.oss.privateKey}")
    private String privateKey;

    @Value("${api.ucloud.oss.bucket}")
    private String bucket;

    @Value("${api.ucloud.oss.region}")
    private String region;


    //cn-bj2 华北1
    public static ObjectConfig config = null;

    public static ObjectAuthorization OBJECT_AUTHORIZER = null;

    public ObjectConfig getConfig() {
        if (config == null) {
            config = new ObjectConfig(region, "ufileos.com");
        }
        return config;
    }


    public ObjectAuthorization getObjectAuthorization() {
        if (OBJECT_AUTHORIZER == null) {
            OBJECT_AUTHORIZER = new UfileObjectLocalAuthorization(publicKey, privateKey);
        }
        return OBJECT_AUTHORIZER;
    }


    public String getPublicKey() {
        return publicKey;
    }

    public String getPrivateKey() {
        return privateKey;
    }

    public String getBucket() {
        return bucket;
    }

    public String getRegion() {
        return region;
    }

    /**
     * 上传文件（以流的形式）
     *
     * @param stream
     * @return
     */
    public String putStream(InputStream stream, String path) {
        String fileName = UUID.randomUUID().toString();
        if (path.contains(".")) {
            String[] item = path.split("\\.");
            fileName = fileName + "." + item[item.length - 1];
        }
        try {
            MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
            String mimeType = fileTypeMap.getContentType(path);
            PutObjectResultBean response = UfileClient.object(getObjectAuthorization(), getConfig())
                    .putObject(stream, stream.available(), mimeType)
                    .nameAs(fileName)
                    .toBucket(bucket)
                    /**
                     * 配置文件存储类型，分别是标准、低频、冷存，对应有效值：STANDARD | IA | ARCHIVE
                     */
                    .withStorageType(StorageType.STANDARD)
                    .execute();
            if (0 == response.getRetCode()) {
                return "/" + fileName;
            }
        } catch (UfileClientException | UfileServerException | IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 上传文件
     *
     * @param filePath
     */
    public String putFile(String filePath, String fileName) {
        if (filePath == null) {
            return null;
        }
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                return null;
            }
            if (!StringUtils.hasLength(fileName)) {
                fileName = file.getName();
            }
            MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
            String mimeType = fileTypeMap.getContentType(file.getName());
            PutObjectResultBean response = UfileClient.object(getObjectAuthorization(), getConfig())
                    .putObject(file, mimeType)
                    .nameAs(fileName)
                    .toBucket(bucket)
                    .execute();
            if (response.getRetCode() == 0) {
                return file.getName();
            }
        } catch (UfileClientException | UfileServerException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 上传文件（异步）
     *
     * @param filePath
     * @param fileName
     */
    public void putFileAsync(String filePath, String fileName) {
        File file = new File(filePath);
        MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
        String mimeType = fileTypeMap.getContentType(file.getName());
        UfileClient.object(getObjectAuthorization(), getConfig())
                .putObject(file, mimeType)
                .nameAs(fileName)
                .toBucket(bucket)
                .executeAsync(new UfileCallback<PutObjectResultBean>() {
                    @Override
                    public void onProgress(long bytesWritten, long contentLength) {

                    }

                    @Override
                    public void onResponse(PutObjectResultBean response) {

                    }

                    @Override
                    public void onError(Request request, ApiError error, UfileErrorBean response) {

                    }
                });
    }

}
